Branchwell

Lumen & Gesso / website · lumengesso.com / app / admin / orders / [id] / page.tsx

1import Link from 'next/link';
2import { notFound, redirect } from 'next/navigation';
3import { getCustomerUser } from '@/app/lib/lumen-auth';
4import { commerceDb } from '@/app/lib/commerce-db';
5import { isAdmin } from '@/app/lib/admin';
6import { displayOrderId, adminStatusLabel } from '@/app/lib/orders';
7import { defaultModelFor, GEMINI_IMAGE_MODEL, OPENAI_IMAGE_MODEL } from '@/app/lib/image-models';
8import { activeProofRevision, customerRevisions, feedbackOnCurrentProof, orderConversation, orderMessageConfig } from '@/app/lib/order-messages';
9import { getOrderCustomer } from '@/app/lib/order-customer';
10import { defaultPromptFor, customStyleStarterPrompt, geminiPromptFor, geminiCustomStylePrompt, aspectSpecFromFrame, withAspect, withLettering, withArtistNote, letteringFontLabel } from '@/app/lib/image-gen';
11import { frameAspect, type Orientation } from '@/app/lib/pricing';
12import type { FrameId } from '@/app/data/frames';
13import { STYLE_CATALOG } from '@/app/data/styleCatalog';
14import { BACKGROUND_COLORS, type BgColorId } from '@/app/data/backgrounds';
15import { AdminEditor } from './editor';
16import { AdminCancel } from './admin-cancel';
17import { PrinterOrder } from './printer-order';
18
19export const dynamic = 'force-dynamic';
20const historyFields = 'id, model, prompt, clean_url, published, created_at';
21
22export default async function AdminOrderPage(
23 { params }: { params: Promise<{ id: string }> },
24) {
25 const { id } = await params;
26
27 const user = await getCustomerUser();
28 if (!user) redirect(`/login?next=/admin/orders/${id}`);
29 if (!isAdmin(user.email)) redirect('/orders');
30
31 const admin = commerceDb();
32 const [{ data: order }, history] = await Promise.all([
33 admin.from('orders').select('*').eq('id', id).single(),
34 admin.from('generations').select(`${historyFields}, rejected_at`).eq('order_id', id).order('created_at', { ascending: false }),
35 ]);
36
37 if (!order) notFound();
38 const customerDetails = getOrderCustomer(order, true);
39
40 let generations = history.data;
41 let historyError = history.error;
42 if (historyError?.code === '42703' && historyError.message.includes('rejected_at')) {
43 console.warn('[portrait history] loading without rejection timestamps', { code: historyError.code });
44 const fallback = await admin.from('generations').select(historyFields).eq('order_id', id).order('created_at', { ascending: false });
45 generations = fallback.data?.map(g => ({ ...g, rejected_at: null })) ?? null;
46 historyError = fallback.error;
47 }
48 if (historyError) console.error('[portrait history] could not load renders', { code: historyError.code });
49
50 const cfg = (order.config ?? {}) as {
51 styleId?: string;
52 commissionName?: string | null;
53 productId?: 'matted' | 'canvas' | 'classic' | 'stretched';
54 size?: string;
55 orientation?: Orientation;
56 frame?: string;
57 matteId?: string | null;
58 bgColorId?: string;
59 bgCustom?: string;
60 fontId?: string;
61 includeName?: boolean;
62 artistNote?: string;
63 };
64 const styleId = cfg.styleId ?? '';
65 const commissionName = cfg.commissionName ?? null;
66 const artistNote = (cfg.artistNote ?? '').trim();
67
68 // Resolve the customer's chosen background colour into { hex, label } —
69 // BUT only when the picked style actually exposes the picker
70 // (hasSolidBackground) AND the order isn't a custom-style commission
71 // (which inherits its background from the uploaded reference). Otherwise
72 // the bgColorId on the order is the picker's default ('warmWhite') from
73 // a skipped step and would be misleading to honour.
74 const styleEntry = STYLE_CATALOG.find(s => s.id === styleId);
75 const hasCustomStyle = !!order.custom_style_url;
76 const showsBackground = !!styleEntry?.hasSolidBackground && !hasCustomStyle;
77 const customerBackground = showsBackground
78 ? (cfg.bgColorId === 'custom'
79 ? { hex: (cfg.bgCustom ?? '').trim() || '#fbf6ea', label: 'Custom' }
80 : cfg.bgColorId && cfg.bgColorId in BACKGROUND_COLORS
81 ? { hex: BACKGROUND_COLORS[cfg.bgColorId as BgColorId].hex, label: BACKGROUND_COLORS[cfg.bgColorId as BgColorId].label }
82 : null)
83 : null;
84
85 // Resolve the customer's lettering selection (name + font) for the
86 // "named" portrait variants. Same gating as bg: only when the style
87 // exposes a name toggle (allowsName), the customer actually turned it
88 // on, AND it isn't a custom-style commission. Used both for the AI
89 // generation directive and the admin-side display badge.
90 const showsLettering = !!styleEntry?.allowsName && !hasCustomStyle && !!cfg.includeName;
91 const letteringName = (cfg.commissionName ?? '').trim();
92 const letteringFontId = cfg.fontId ?? null;
93 const customerLettering = showsLettering && letteringName && letteringFontId
94 ? { name: letteringName, fontId: letteringFontId, fontLabel: letteringFontLabel(letteringFontId) ?? letteringFontId }
95 : null;
96 const revisions = customerRevisions(order.config, order.revision_note, order.updated_at);
97 const messages = orderConversation(order.config, order.revision_note, order.updated_at);
98 const customStyleDescription = (order.custom_style_description as string | null) ?? null;
99 const customStyleAnalyzedAt = (order.custom_style_analyzed_at as string | null) ?? null;
100 // Each model gets its OWN prompt — they're prompted differently:
101 // • OpenAI uses the full prose image brief. For custom
102 // styles that's the two-image starter prompt, with GPT-4o Vision's
103 // cached style description baked in (its /images/edits endpoint
104 // can't see the style image, only read a description of it).
105 // • Gemini uses the compact "ingredient" prompt — the style essence
106 // for catalog styles, or (for custom orders) a lean prompt that
107 // leans on the uploaded style reference it receives directly.
108 // The editor keeps both and swaps on model switch (remembering edits).
109 // Shape the prompts for the customer's frame aspect so the render is
110 // composed for the real canvas, not a square. No-op for square frames.
111 const aspectSpec = aspectSpecFromFrame(frameAspect(cfg.productId, cfg.size, cfg.orientation ?? 'portrait'));
112 // The customer's bg colour is woven NATIVELY into the catalog prompts
113 // for hasSolidBackground styles via {{BG_HEX}} / {{BG_LABEL}}
114 // placeholders that defaultPromptFor / geminiPromptFor substitute in.
115 // Pass null for custom-style orders (the reference defines the ground)
116 // and for non-hasSolidBackground styles (their prompts carry no
117 // placeholders, so substitution is a no-op anyway).
118 const letteringDirective = customerLettering
119 ? { name: customerLettering.name, fontId: customerLettering.fontId, include: true }
120 : null;
121 // Wrappers compose around the bg-substituted base prompt: aspect →
122 // lettering → artist note. Artist note sits OUTERMOST (first thing the
123 // model reads) and is applied uniformly across all four paths.
124 // geminiCustomStylePrompt still accepts the note for backwards compat
125 // but we pass null here to avoid duplicating it with withArtistNote.
126 const openaiPrompt = withArtistNote(
127 withLettering(
128 withAspect(
129 hasCustomStyle
130 ? customStyleStarterPrompt(commissionName, customStyleDescription)
131 : defaultPromptFor(styleId, commissionName, customerBackground),
132 aspectSpec,
133 ),
134 letteringDirective,
135 ),
136 artistNote,
137 );
138 const geminiPrompt = withArtistNote(
139 withLettering(
140 withAspect(
141 hasCustomStyle
142 ? geminiCustomStylePrompt(null)
143 : geminiPromptFor(styleId, customerBackground),
144 aspectSpec,
145 ),
146 letteringDirective,
147 ),
148 artistNote,
149 );
150 const initialPrompts = {
151 [OPENAI_IMAGE_MODEL]: openaiPrompt,
152 [GEMINI_IMAGE_MODEL]: geminiPrompt,
153 } as const;
154
155 const customer = await customerDetails;
156 const orderRef = displayOrderId(order.id);
157 const shipping = order.shipping_address as {
158 name?: string | null;
159 address?: {
160 line1?: string | null;
161 line2?: string | null;
162 city?: string | null;
163 state?: string | null;
164 postal_code?: string | null;
165 country?: string | null;
166 } | null;
167 } | null;
168 const address = shipping?.address;
169 const cityAndState = [address?.city, address?.state].filter(Boolean).join(', ');
170 const shippingLines = [
171 address?.line1,
172 address?.line2,
173 [cityAndState, address?.postal_code].filter(Boolean).join(' '),
174 address?.country,
175 ].filter(line => typeof line === 'string' && line.trim());
176
177 return (
178 <main className="orders">
179 <div className="orders__inner" style={{ maxWidth: 1100 }}>
180 <Link href="/admin" className="orders__back">← All commissions</Link>
181 <h1 className="orders__title">{customer.name || orderRef}</h1>
182 <p className="orders__back admin-order__summary">
183 {customer.name && <span>{orderRef}</span>}
184 {styleId && <span>{styleEntry?.name ?? styleId}</span>}
185 <span className={`statuschip statuschip--${order.status}`}>{adminStatusLabel(order.status)}</span>
186 </p>
187
188 <section className="admin-editor__panel admin-order__details" aria-label="Customer and shipping details">
189 <div>
190 <h2 className="orderdetail__photoshead">Customer contact</h2>
191 <a href={`mailto:${order.user_email}`}>{order.user_email}</a>
192 {customer.phone && <span>{customer.phone}</span>}
193 </div>
194 <div>
195 <h2 className="orderdetail__photoshead">Shipping address</h2>
196 {shipping?.name || shippingLines.length > 0 ? (
197 <address>
198 {shipping?.name && <span>{shipping.name}</span>}
199 {shippingLines.map((line, i) => <span key={i}>{line}</span>)}
200 {shippingLines.length === 0 && <span>Address not provided</span>}
201 </address>
202 ) : <span>Address not provided</span>}
203 </div>
204 </section>
205
206 <PrinterOrder orderId={order.id} prodigiOrderId={order.prodigi_order_id} />
207
208 <AdminEditor
209 orderId={order.id}
210 status={order.status}
211 currentProofId={order.current_generation_id}
212 proofRevision={activeProofRevision(order)}
213 pendingFeedback={feedbackOnCurrentProof(order)?.note ?? ''}
214 sentRevisions={orderMessageConfig(order.config).sentRevisions}
215 petPhotoUrls={(order.pet_photo_urls as string[]) ?? []}
216 customStyleUrl={(order.custom_style_url as string | null) ?? null}
217 customStyleDescription={customStyleDescription}
218 customStyleAnalyzedAt={customStyleAnalyzedAt}
219 artistNote={artistNote}
220 revisions={revisions}
221 messages={messages}
222 initialModel={defaultModelFor(styleId)}
223 initialPrompts={initialPrompts}
224 customerBackground={customerBackground}
225 customerLettering={customerLettering ? { name: customerLettering.name, fontLabel: customerLettering.fontLabel } : null}
226 frameConfig={{
227 productId: cfg.productId ?? 'matted',
228 size: cfg.size ?? '12x16',
229 orientation: cfg.orientation ?? 'portrait',
230 frame: (cfg.frame ?? 'black') as FrameId,
231 matteId: cfg.matteId ?? null,
232 }}
233 generations={(generations ?? []).map(g => ({
234 id: g.id,
235 model: g.model,
236 prompt: g.prompt,
237 cleanUrl: g.clean_url,
238 published: order.current_generation_id ? g.id === order.current_generation_id : g.published,
239 rejectedAt: g.rejected_at as string | null,
240 createdAt: g.created_at,
241 }))}
242 historyUnavailable={!!historyError}
243 />
244
245 <AdminCancel
246 orderId={order.id}
247 status={order.status}
248 hasProdigi={!!order.prodigi_order_id}
249 />
250 </div>
251 </main>
252 );
253}